/*******************************************************************************
 * Copyright (c) 2004, 2009 Blue Bamboo International Inc. 
 * All rights reserved.
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *******************************************************************************/

package com.bambamboo.st.socket.server.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bambamboo.st.IProcessor;
import com.bambamboo.st.util.HexString;

/**
 * DOCME
 * 
 * @author Nick.Tan
 * @since 1.0.0
 */
public class DefaultIoHandler extends AbstractIoHandler {

	private static final Logger logger = LoggerFactory.getLogger(DefaultIoHandler.class);

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		IoBuffer buffer = ((IoBuffer) message);

		IProcessor processor = getConfigurationBean().getProcessor();
		byte[] requestBuf = new byte[buffer.limit()];
		buffer.get(requestBuf);
		logger.debug("request data from <{}>:\n{}", session.getRemoteAddress(), HexString.dump(requestBuf));

		byte[] byResp = processor.getResponse(requestBuf);
		if (byResp != null) {
			IoBuffer out = IoBuffer.allocate(byResp.length);
			out.put(byResp);
			out.flip();
			session.write(out);
		}
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
		logger.info("session create: " + session.getRemoteAddress());
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session);
		logger.info("session closed: " + session.getRemoteAddress());
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
		logger.info("session opened: " + session.getRemoteAddress());
	}

}
